//
//  CustomerTagVC.swift
//  Employee
//
//  Created by tancheng on 2018/7/24.
//  Copyright © 2018年 remotevillage. All rights reserved.
//

import Foundation
import UIKit
import SwiftyJSON
import RxSwift

class CustomerTagFlowLayout: UICollectionViewFlowLayout {
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        
        let answer = super.layoutAttributesForElements(in: rect)
    
        for (index,value) in (answer?.enumerated())!
        {
            
            
            if value.indexPath.row == 0  { continue }
            
                let currentLayoutAttributes :UICollectionViewLayoutAttributes = value//当前item
                let prevLayoutAttributes:UICollectionViewLayoutAttributes = answer![index-1] //上一个item
                let maximumSpacing = 10 //最大间距
                let origin = prevLayoutAttributes.frame.maxX
                
                if(origin + CGFloat(maximumSpacing) + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width - 20) {
                    var frame = currentLayoutAttributes.frame;
                    frame.origin.x = origin + CGFloat(maximumSpacing);
                    currentLayoutAttributes.frame = frame;
                }
             //print(value.indexPath,currentLayoutAttributes.frame)
        }
 
       
        
        return answer
        
        
    }
    
}

class CustomerTagVC: BaseVC {
    
    fileprivate let disposeBag = DisposeBag()
    
    var tagData: [CustomerTagCategoryModel] = [] //
    var selectedData: [CustomerTagModel] = [] //
    
    var pastTags: [TagModel] = []
    var customerId: String!
    var updateClosure: (([TagModel])->())?
    
    //
    lazy var tagCollectionView: UICollectionView = {
        let layout = CustomerTagFlowLayout.init()
        
        let cv = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout)
        cv.dataSource = self
        cv.delegate = self
        cv.showsVerticalScrollIndicator = false
        cv.register(UINib.init(nibName: "CustomerTagCell", bundle: nil), forCellWithReuseIdentifier: "CustomerTagCell")
        
        cv.register(UINib.init(nibName: "CustomerTagReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "CustomerTagReusableView")
        
       
        return cv
    }()
    
    lazy var selBgView: UIView = {
       let v = UIView()
        v.backgroundColor = .white
        return v
    }()
    
    lazy var selCollectionView: UICollectionView = {
        let layout = CustomerTagFlowLayout.init()
        //layout.estimatedItemSize = CGSize(width: 70, height: 38)//预估size
        let cv = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout)
        cv.dataSource = self
        cv.delegate = self
        cv.isScrollEnabled = false
        cv.showsVerticalScrollIndicator = false
        cv.register(UINib.init(nibName: "CustomerTagCell", bundle: nil), forCellWithReuseIdentifier: "CustomerTagCell")
        cv.register(UINib.init(nibName: "CustomerTagReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "CustomerTagReusableView")
        //cv.register(UINib.init(nibName: "CustomerTagFooterReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "CustomerTagFooterReusableView")
        return cv
    }()
    
    lazy var countBgView: UIView = {
        let v = UIView()
        v.backgroundColor = .white
        return v
    }()
    lazy var selCountLab: UILabel = {
       let lab = UILabel()
        lab.font = GlobalConfig.system14Font
        lab.textColor = GlobalConfig.TextDeepColor
        return lab
    }()
    
    lazy var noSelLab:UILabel = {
        let lab = UILabel()
        lab.font = GlobalConfig.system16Font
        lab.textColor = GlobalConfig.TextDeepColor.withAlphaComponent(0.5)
        lab.text = "TA还没有标签"
        return lab
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
     
        setupUI()
        getTags()
        
    }
    
    func getTags() {
        
      let _ =  CustomerRequest.shared.getTagTree(success: { (data) in
            
          self.tagData = data
          self.configureSelData()
        
        }) {
            self.showHint("获取标签失败")
            self.navigationController?.popViewController(animated: true)
        }
        
    }
    
    func setupUI() {
        title = "标签管理"
        view.backgroundColor = UIColor.hex("#f5f5f5")
        
        let btn = UIButton(type: .custom)
        btn.titleLabel?.font = GlobalConfig.system16Font
        btn.setTitle("保存", for: .normal)
        btn.setTitleColor(UIColor.hex("#66A6FF"), for: .normal)
        btn.frame = CGRectMake(0, 0, 44, 44)
        btn.rx.tap.subscribe(onNext: {[weak self] (_) in
            self?.save()
        }).disposed(by: disposeBag)
        let item = UIBarButtonItem.init(customView: btn)
        navigationItem.rightBarButtonItem = item
        
        view.addSubview(countBgView)
        view.addSubview(tagCollectionView)
        view.addSubview(selBgView)
        selBgView.addSubview(selCollectionView)
        countBgView.addSubview(selCountLab)
        
        view.bringSubview(toFront: countBgView)//
        selBgView.backgroundColor = UIColor.hex("#f5f5f5")
        
        let tipBgView = UIView()
        tipBgView.backgroundColor = .white
        selBgView.addSubview(tipBgView)
        tipBgView.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(62)
        }
        
        let tipLab = UILabel()
        tipLab.font = GlobalConfig.system14Font
        tipLab.textColor = GlobalConfig.TextDeepColor.withAlphaComponent(0.5)
        tipLab.text = "点击以下标签以添加"
        tipBgView.addSubview(tipLab)
        tipLab.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
        }
        
        //
        countBgView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(60)
        }
        
        selCountLab.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.leading.equalToSuperview().offset(10)
        }
        
        selBgView.frame = CGRectMake(0, 60, view.bounds.width, 106+72)
        
        selCollectionView.snp.makeConstraints { (make) in
             make.leading.top.trailing.equalToSuperview()
             make.bottom.equalToSuperview().offset(-72)
        }
        tagCollectionView.snp.makeConstraints { (make) in
            make.top.equalTo(countBgView.snp.bottom)
            make.leading.bottom.trailing.equalToSuperview()
        }
        //tagCollectionView.frame = CGRectMake(0, 60, view.bounds.width, view.bounds.height-60)
        if #available(iOS 11, *) {
            tagCollectionView.contentInsetAdjustmentBehavior = .never
             selCollectionView.contentInsetAdjustmentBehavior = .never
        }
        tagCollectionView.contentInset = UIEdgeInsetsMake(selBgView.bounds.height, 0, 0, 0)
        
        selCollectionView.backgroundColor = .white
        tagCollectionView.backgroundColor = .white
        
        //
        let pan =  tagCollectionView.panGestureRecognizer
        view.addGestureRecognizer(pan)
        
        //
        
        
    }

    func configureSelData() {
        
        for tag in pastTags {
            for model in tagData {
                for item in model.tags {
                    if tag.id == item.id {
                        item.isSelected = true
                        selectedData.append(item)
                        break
                }
            }
        }
    }
        tagCollectionView.reloadData()
        selCollectionView.reloadData()
        updateSelHeight()
    }
    
}

extension CustomerTagVC: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        if collectionView == tagCollectionView {
            return tagData.count
        }
        return  1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       if collectionView == tagCollectionView {
            return tagData[section].tags.count
        }
        return selectedData.count

    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomerTagCell", for: indexPath) as! CustomerTagCell
        
        if collectionView == tagCollectionView {
            let model = tagData[indexPath.section].tags[indexPath.row]
            cell.tagName.text = model.name
            cell.selectedBgView.backgroundColor = model.isSelected ? UIColor.hex("#66A6FF") : UIColor.hex("#f5f5f5")
            cell.tagName.textColor = model.isSelected ? UIColor.white : GlobalConfig.TextDeepColor
            cell.deleteBtn.isHidden = true
        }else {
            cell.tagName.text = selectedData[indexPath.row].name
            cell.selectedBgView.backgroundColor = UIColor.hex("#66A6FF")
            cell.tagName.textColor = UIColor.white
            cell.deleteBtn.isHidden = false
        }
        
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        //CustomerTagFooterReusableView
        
 //       if kind == UICollectionElementKindSectionFooter {
//
//            let footer = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "CustomerTagFooterReusableView", for: indexPath) as! CustomerTagFooterReusableView
//
//                return footer
 //       }else{
        
            let reusableView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "CustomerTagReusableView", for: indexPath) as! CustomerTagReusableView
            
        
        if collectionView == tagCollectionView {
            let model = tagData[indexPath.section]
            reusableView.title.text = model.categoryName
        }else{
            
            reusableView.title.text = ""
        }
            return reusableView
            
//        }
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if collectionView == tagCollectionView {
            let model = tagData[indexPath.section].tags[indexPath.row]
            return CGSize(width: model.itemWidth, height: model.itemHeight)
        }
        return CGSize(width: selectedData[indexPath.row].addItemWidth, height: selectedData[indexPath.row].itemHeight)
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(0, 10, 20, 10)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        if collectionView == tagCollectionView {
            return CGSize(width: collectionView.bounds.width, height: 28)
        }
        return CGSize.zero
    }

//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
//        if collectionView != tagCollectionView {
//            return CGSize(width: collectionView.bounds.width, height: 72)
//        }
//        return CGSize.zero
//    }
    
   
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10 //行间距 item上下间距
    }
    
    
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if collectionView == tagCollectionView {
            let model = tagData[indexPath.section].tags[indexPath.row]
            //let json = JSON.init(model)
            //let addModel = CustomerTagModel.init(json: json)
            if !model.isSelected {
            
                selectedData.append(model)
            }else {
                selectedData.removeObject(model)
            }
            model.isSelected = !model.isSelected
            
            updateSelHeight()
            UIView.performWithoutAnimation {//取消刷新动画
               collectionView.reloadData()
                selCollectionView.reloadData()
            }

        }else{
            let model = selectedData[indexPath.row]
             model.isSelected = false
    
            selectedData.removeObject(model)
            updateSelHeight()
            UIView.performWithoutAnimation {//取消刷新动画
                collectionView.reloadData()
                 tagCollectionView.reloadData()
            }
        }
        
    }
    
    ///
    func selHeight() -> CGFloat {
        
        var x: CGFloat = 10
        var height: CGFloat = 38 + 20
        for (_,item) in selectedData.enumerated() {
            
            if x + item.addItemWidth > selCollectionView.collectionViewLayout.collectionViewContentSize.width - 10 {
                x = 10
                height += 38 + 10
            }
            x += item.addItemWidth + 10
        }
        
        return height
    }
    
    func updateSelHeight() {
        
        if selectedData.count == 0 {
            selCountLab.isHidden = true
            
//            selBgView.frame.origin.y = -60
//            tagCollectionView.frame.origin.y = 0
//            tagCollectionView.frame.size.height = view.bounds.height
            selBgView.addSubview(noSelLab)
            noSelLab.snp.makeConstraints({ (make) in
                make.centerY.equalToSuperview().multipliedBy(0.5)
                make.centerX.equalToSuperview()
            })
            return
        }else{
            selCountLab.isHidden = false
            //selBgView.frame.origin.y = 60
            //tagCollectionView.frame.origin.y = 60
            //tagCollectionView.frame.size.height = view.bounds.height-60
            noSelLab.removeFromSuperview()
        }
        
        var height: CGFloat = 72
        
        if selHeight() < 106 {
            height = CGFloat(106 + 72)
        }else{
            height = selHeight() + CGFloat(72)
        }
        
        tagCollectionView.contentInset = UIEdgeInsetsMake(height, 0, 0, 0)
        selBgView.frame.size.height = height
        let offsetY = tagCollectionView.contentOffset.y
        let insetTop = tagCollectionView.contentInset.top
        selBgView.frame.origin.y = countBgView.bounds.height - offsetY - insetTop
        selCountLab.text = "已添加" + " \(selectedData.count) " + "个标签"
        
    }
    
}

extension CustomerTagVC {
    func save() {
        var ids = ""
        var selData: [TagModel] = []
        for item in selectedData {
            ids += item.id + ","
            let dic = ["tagId":item.id,"tagName":item.name]
            let model = TagModel.init(json: JSON(dic))
            selData.append(model)
        }
        if !ids.isEmpty {
            ids.removeLast()
        }
        
        var send = CustomerTagSend()
        send.customerId = customerId
        send.tagIds = ids
       let _ = CustomerRequest.shared.updateTags(send: send, success: {
            self.updateClosure?(selData)
        
            runOnMainThread {
                self.showHint("保存成功")
            }
        
           let _ = runIndelay(1.5, task: {
                self.navigationController?.popViewController(animated: true)
            })
            
        }) {
            
        }
        
        
        
    }
    
}


extension CustomerTagVC : UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView == tagCollectionView {
            let offsetY = scrollView.contentOffset.y
            let insetTop = scrollView.contentInset.top
            selBgView.frame.origin.y = countBgView.bounds.height - offsetY - insetTop
        }
    }
}
